package data

import (
	"context"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/redis/go-redis/v9"
	"hello-kratos/kratos-server/internal/conf"
	"time"
)

type Redis struct {
	client *redis.Client
	l      *log.Helper
}

func NewRedis(data *conf.Data, logger log.Logger) (*Redis, func(), error) {
	opt, err := redis.ParseURL(data.GetRedis().Dsn)
	if err != nil {
		return nil, nil, err
	}
	rTime, err := time.ParseDuration(data.Redis.ReadTimeout)
	if err != nil {
		return nil, nil, err
	}
	opt.ReadTimeout = rTime
	wTime, err := time.ParseDuration(data.Redis.WriteTimeout)
	if err != nil {
		return nil, nil, err
	}
	opt.WriteTimeout = wTime
	l := log.NewHelper(logger)
	client := redis.NewClient(opt)
	cleanup := func() {
		l.Info("closing redis connection")
		if err = client.Close(); err != nil {
			l.Errorf("close redis connection error: %v", err)
		}
	}
	if err = client.Ping(context.Background()).Err(); err != nil {
		return nil, cleanup, err
	}
	return &Redis{
		client: client,
		l:      l,
	}, cleanup, nil
}
